﻿using System;
using System.ComponentModel;

namespace RockBus.Utilities
{
    public static class Conversions
    {
        public static TTo ConvertWithTypeConverter<TFrom, TTo>(TFrom from)
        {
            var sourceType = typeof(TFrom);
            var destinationType = typeof(TTo);

            var converter = TypeDescriptor.GetConverter(sourceType);
            if ((converter != null) &&
                (converter.CanConvertTo(destinationType)))
            {
                return (TTo)converter.ConvertTo(from, destinationType);
            }

            converter = TypeDescriptor.GetConverter(destinationType);
            if ((converter != null) &&
                (converter.CanConvertFrom(sourceType)))
            {
                return (TTo)converter.ConvertFrom(from);
            }

            throw new Exception(string.Format("Can't convert from type {0} to type {1}.",
                sourceType.FullName,
                destinationType.FullName));
        }
    }
}
